'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import Image from 'next/image';
import HtmlLink from '@/app/components/common/html-link';
import { VideoSelect } from '@/lib/database/repositories/video-repository';

interface CarouselProps {
  videos: VideoSelect[];
}

export default function Carousel({ videos }: CarouselProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [touchStart, setTouchStart] = useState(0);
  const [touchEnd, setTouchEnd] = useState(0);
  const [isSwiping, setIsSwiping] = useState(false);
  const [isClick, setIsClick] = useState(false);
  const [swipeDirection, setSwipeDirection] = useState<'left' | 'right' | null>(null);
  const autoplayTimerRef = useRef<NodeJS.Timeout | null>(null);
  const [isSmallScreen, setIsSmallScreen] = useState(false);
  const carouselRef = useRef<HTMLDivElement>(null);
  
  // 停止自动轮播
  const stopAutoplay = useCallback(() => {
    if (autoplayTimerRef.current) {
      clearInterval(autoplayTimerRef.current);
      autoplayTimerRef.current = null;
    }
  }, []);

  // 开始自动轮播
  const startAutoplay = useCallback(() => {
    stopAutoplay();
    autoplayTimerRef.current = setInterval(() => {
      setCurrentIndex((prevIndex) => (prevIndex + 1) % videos.length);
    }, 5000);
  }, [stopAutoplay, videos.length]);
  
  // 手动切换到下一张
  const nextSlide = useCallback(() => {
    stopAutoplay();
    setCurrentIndex((prevIndex) => (prevIndex + 1) % videos.length);
    // 使用setTimeout确保状态更新后再启动自动轮播
    setTimeout(() => startAutoplay(), 0);
  }, [videos.length, stopAutoplay, startAutoplay]);

  // 手动切换到上一张
  const prevSlide = useCallback(() => {
    stopAutoplay();
    setCurrentIndex((prevIndex) => (prevIndex - 1 + videos.length) % videos.length);
    // 使用setTimeout确保状态更新后再启动自动轮播
    setTimeout(() => startAutoplay(), 0);
  }, [videos.length, stopAutoplay, startAutoplay]);
  
  // 直接跳转到指定幻灯片
  const goToSlide = useCallback((index: number) => {
    stopAutoplay();
    setCurrentIndex(index);
    // 使用setTimeout确保状态更新后再启动自动轮播
    setTimeout(() => startAutoplay(), 0);
  }, [stopAutoplay, startAutoplay]);
  
  // 检测小屏幕的媒体查询
  useEffect(() => {
    // 只在客户端运行
    if (typeof window === 'undefined') return;
    
    const mediaQuery = window.matchMedia('(max-width: 767px)');
    const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {
      setIsSmallScreen(e.matches);
    };
    
    // 初始设置
    handleChange(mediaQuery);
    
    // 添加监听器
    mediaQuery.addEventListener('change', handleChange);
    
    // 清理
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);
  
  // 自动轮播
  useEffect(() => {
    startAutoplay();
    return () => stopAutoplay();
  }, [startAutoplay, stopAutoplay]);
  
  // 为轮播图添加触摸事件监听器，使用 passive: false 选项
  useEffect(() => {
    const carousel = carouselRef.current;
    if (!carousel) return;

    const handleTouchStartEvent = (e: TouchEvent) => {
      // 不要立即阻止默认行为，只记录初始触摸位置
      stopAutoplay();
      setTouchStart(e.touches[0].clientX);
      setIsSwiping(true);
      setIsClick(true);
      setSwipeDirection(null);
    };

    const handleTouchMoveEvent = (e: TouchEvent) => {
      if (!isSwiping) return;
      
      const currentTouch = e.touches[0].clientX;
      setTouchEnd(currentTouch);
      
      // 只在明显滑动时阻止默认行为
      const moveDistance = Math.abs(touchStart - currentTouch);
      if (moveDistance > 5) {
        // 当确认是滑动操作时才阻止默认行为
        e.preventDefault();
        setIsClick(false);
        
        // 确定滑动方向用于视觉反馈
        if (touchStart - currentTouch > 20) {
          setSwipeDirection('left');
        } else if (touchStart - currentTouch < -20) {
          setSwipeDirection('right');
        } else {
          setSwipeDirection(null);
        }
      }
    };

    const handleTouchEndEvent = () => {
      if (!isSwiping) return;
      
      setIsSwiping(false);
      
      // 如果是点击操作，不要触发轮播图切换，让链接正常跳转
      if (isClick) {
        setIsClick(false);
        startAutoplay();
        return;
      }
      
      // 降低小屏幕上的滑动阈值，提高灵敏度
      const swipeThreshold = isSmallScreen ? 30 : 50;
      const moveDistance = Math.abs(touchStart - touchEnd);
      
      // 只有当滑动距离超过阈值时才视为滑动操作
      if (moveDistance > 10) {
        if (touchStart - touchEnd > swipeThreshold) {
          // 向左滑动，显示下一张
          nextSlide();
        } else if (touchStart - touchEnd < -swipeThreshold) {
          // 向右滑动，显示上一张
          prevSlide();
        } else {
          // 如果没有足够的滑动距离，恢复自动轮播
          startAutoplay();
        }
      } else {
        // 如果移动距离很小，视为点击而非滑动操作
        // 不处理，让默认的链接点击行为正常执行
        startAutoplay();
      }
      
      setSwipeDirection(null);
    };

    const handleTouchCancelEvent = () => {
      setIsSwiping(false);
      setIsClick(false);
      setSwipeDirection(null);
      startAutoplay();
    };

    // 添加事件监听器，设置 passive: false
    carousel.addEventListener('touchstart', handleTouchStartEvent as EventListener);
    carousel.addEventListener('touchmove', handleTouchMoveEvent as EventListener, { passive: false } as AddEventListenerOptions);
    carousel.addEventListener('touchend', handleTouchEndEvent);
    carousel.addEventListener('touchcancel', handleTouchCancelEvent);

    return () => {
      // 移除事件监听器
      carousel.removeEventListener('touchstart', handleTouchStartEvent as EventListener);
      carousel.removeEventListener('touchmove', handleTouchMoveEvent as EventListener);
      carousel.removeEventListener('touchend', handleTouchEndEvent);
      carousel.removeEventListener('touchcancel', handleTouchCancelEvent);
    };
  }, [isSwiping, touchStart, touchEnd, isSmallScreen, startAutoplay, stopAutoplay, nextSlide, prevSlide, isClick]);

  if (!videos.length) {
    return null;
  }

  return (
    <div className="relative w-full overflow-hidden rounded-none sm:rounded-xl">
      {/* 轮播图容器 */}
      <div 
        ref={carouselRef}
        className="relative aspect-[16/9] sm:aspect-[21/9] md:aspect-[24/10] w-full rounded-none sm:rounded-xl overflow-hidden"
      >
        {/* 滑动指示器 - 仅小屏幕显示 */}
        {isSwiping && swipeDirection && (
          <div className="md:hidden absolute size-full inset-y-0 z-30 flex items-center pointer-events-none">
            {swipeDirection === 'left' && (
              <div className="absolute right-2 bg-background-darker/70 text-white p-2 rounded-full">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </div>
            )}
            {swipeDirection === 'right' && (
              <div className="absolute left-2 bg-background-darker/70 text-white p-2 rounded-full">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
              </div>
            )}
          </div>
        )}
      
        {videos.map((video, index) => (
          <HtmlLink 
            key={video.id} 
            href={`/detail/${video.id}`}
            className={`absolute inset-0 transition-opacity duration-700 rounded-none sm:rounded-xl overflow-hidden ${
              index === currentIndex ? 'opacity-100 z-10' : 'opacity-0 z-0'
            }`}
          >
            {/* 加载中状态 */}
            {isLoading && index === currentIndex && (
              <div className="absolute inset-0 flex items-center justify-center bg-background-darker/95 z-20">
                <div className="inline-block h-8 w-8 sm:h-10 sm:w-10 animate-spin rounded-full border-4 border-solid border-gray-200 border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" />
              </div>
            )}
            
            <Image
              src={video.carouselPic || video.vodPic || '/images/placeholder.jpg'}
              alt={video.vodName || '影片'}
              fill
              sizes="(max-width: 640px) 100vw, (max-width: 1024px) 100vw, 100vw"
              priority={index === 0}
              className={`object-cover rounded-none sm:rounded-xl ${isLoading && index === currentIndex ? 'opacity-0' : 'opacity-100'}`}
              onLoad={() => index === currentIndex && setIsLoading(false)}
            />
            
            {/* 渐变遮罩 */}
            <div className="absolute inset-0 bg-gradient-to-t from-background-darker/95 via-background-dark/40 to-black/20 opacity-80 rounded-none sm:rounded-xl" />
            
            {/* 影片信息 */}
            <div className="absolute bottom-0 left-0 right-0 p-3 sm:p-4 md:p-10 md:pl-16 md:pb-16 pb-8">
              <h2 className="text-white text-lg sm:text-xl md:text-3xl font-bold mb-2 sm:mb-3 md:mb-4">{video.vodName}</h2>
              <div className="flex items-center gap-2 sm:gap-4 text-xs sm:text-sm md:text-base text-gray-200 mb-2 md:mb-4">
                {video.vodScore && (
                  <span className="bg-red-600 text-white px-1.5 py-0.5 rounded text-xs sm:text-sm">
                    {video.vodScore.toFixed(1)}分
                  </span>
                )}
                <span>{video.vodYear}</span>
                <span>{video.typeName}</span>
              </div>
              <p className="mt-1 sm:mt-3 md:mt-4 text-xs sm:text-sm text-gray-300 line-clamp-2 md:w-2/3">
                {video.vodContent || video.vodSub || '暂无简介'}
              </p>
            </div>
          </HtmlLink>
        ))}
      </div>

      {/* 小屏幕滑动提示 - 首次加载时显示 */}
      <div className="md:hidden absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-20 text-white/70 text-xs bg-background-darker/50 px-3 py-1.5 rounded-full pointer-events-none animate-pulse">
        左右滑动切换
      </div>

      {/* 左右箭头控制 - 非移动端显示 */}
      <div className="hidden md:block">
        <button
          onClick={prevSlide}
          className="absolute left-2 sm:left-4 top-1/2 -translate-y-1/2 z-20 bg-background-darker/70 text-white p-1.5 sm:p-2 rounded-full hover:bg-background-darker/90 transition-colors"
          aria-label="上一张"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-5 w-5 sm:h-6 sm:w-6"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 19l-7-7 7-7"
            />
          </svg>
        </button>
        <button
          onClick={nextSlide}
          className="absolute right-2 sm:right-4 top-1/2 -translate-y-1/2 z-20 bg-background-darker/70 text-white p-1.5 sm:p-2 rounded-full hover:bg-background-darker/90 transition-colors"
          aria-label="下一张"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-5 w-5 sm:h-6 sm:w-6"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 5l7 7-7 7"
            />
          </svg>
        </button>
      </div>

      {/* 导航指示点 */}
      <div className="absolute bottom-3 left-1/2  -translate-x-1/2 z-20 flex space-x-1 sm:space-x-2">
        {videos.map((_, index) => (
          <button
            key={index}
            onClick={() => goToSlide(index)}
            className={`w-2 h-2 sm:w-2.5 sm:h-2.5 rounded-full transition-all ${
              index === currentIndex
                ? 'bg-red-600 scale-110'
                : 'bg-gray-500/60 hover:bg-gray-400/70'
            }`}
            aria-label={`切换到第${index + 1}张图片`}
          />
        ))}
      </div>
    </div>
  );
} 